package com.lsk.admin.AdminSystem;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import com.lsk.util.*;
import net.sf.json.JSONObject;

import java.io.File;
import java.util.*;

/**
 * 后台系统设置controller
 * Created by Administrator on 2017/12/15 0015.
 */
public class AdminSystemController extends Controller {
    static AdminSystemService adminSystemService= Duang.duang(AdminSystemService.class);
    Cache cache= Redis.use(PropKit.get("cache.name"));
    /**
     * 角色列表
     */
    public void roleList(){
        String currentPage = getPara("currentPage");
        String size = getPara("size");
        Map<String,String[]> map=getParaMap();
        String userId= getSession().getAttribute("userId").toString();
        ReturnData data = adminSystemService.roleList(map,userId);
        PageUtil<List<Record>> menu= (PageUtil<List<Record>>) data.getData();
        setAttr("menu",menu);
        setAttr("currentPage",currentPage);
        setAttr("size",size);
        renderJsp("adminRole.jsp");
    }
    /**
     * 添加角色页面
     */
    public void addRole(){
        String userId= getSession().getAttribute("userId").toString();
//        ReturnData data = adminSystemService.findAllResource("user",userId);
//        setAttr("data",data);
        renderJsp("role-add.jsp");
    }
    /**
     * 赋权列表
     */
    public void givePermission(){
        String userId=getSession().getAttribute("userId").toString();
        String permissionId=getPara("permissionId");
        List<Record> oneList=adminSystemService.getPermissionByUserIdAndPermissionId(userId,permissionId);//当前用户所具有的的权限
        String type=getPara("type");//类型
        String id=getPara("id");//id
        List<Record> twoList=new ArrayList<>();
        if ("role".equals(type)){//角色
            twoList=adminSystemService.selectPermissionByRoleId(id);
        }else if ("user".equals(type)){//用户
            twoList=adminSystemService.selectPermissionByUserId(id);
        }
        setAttr("oneList",oneList);
        setAttr("twoList",twoList);
        setAttr("type",type);
        setAttr("id",id);
        setAttr("permissionId",permissionId);
        renderJsp("permissionList.jsp");
    }
    /**
     * 保存权限
     */
    @Before(Tx.class)
    public void saveRoleOrUserPermission(){
        Map<String,String[]> map=getParaMap();
        ReturnData result=adminSystemService.saveRoleOrUserPermissionService(map);
        renderJson(result);
    }


    /**
     * 权限树
     */
    public void permissionTree(){
        String type=getPara("type");
        String id=getPara("id");
        String userId=getSession().getAttribute("userId").toString();
        List<Record> oneList=adminSystemService.treePermissionByUserId(userId);//当前用户所具有的的权限
        List<Record> twoList=null;
        if ("role".equals(type)){//角色
            twoList=adminSystemService.selectPermissionByRoleId(id);
        }else if ("user".equals(type)){
            twoList=adminSystemService.selectPermissionByUserId(id);
        }
        setAttr("oneList",oneList);
        setAttr("twoList",twoList);
        setAttr("type",type);
        setAttr("id",id);
        //renderJsp("permissionTree.jsp");
        renderJsp("permissionList1.jsp");
    }

    /**
     * 一级权限
     */
    public void onePermission(){
        String type=getPara("type");
        String id=getPara("id");
        String userId=getSession().getAttribute("userId").toString();
        List<Record> oneList=adminSystemService.onePermissionService(userId);//当前用户所具有一级权限
        List<Record> roleOneList=null;
        List<Record> userOneList=null;
        if ("role".equals(type)){//角色
            roleOneList=adminSystemService.selectPermissionByRoleId(id);
        }else if ("user".equals(type)){
            userOneList=adminSystemService.selectPermissionByUserId(id);
        }
        setAttr("roleOneList",roleOneList);
        setAttr("userOneList",userOneList);
        setAttr("oneList",oneList);
        setAttr("type",type);
        setAttr("id",id);
        //renderJsp("permissionTree.jsp");
        renderJsp("permissionList1.jsp");
    }
    /**
     * 二级菜单权限
     */
    public void twoPermission(){
        String type=getPara("type");
        String id=getPara("id");
        String permissionId=getPara("onePermissionId");
        String userId=getSession().getAttribute("userId").toString();
        List<Record> twoList=adminSystemService.twoPermissionService(permissionId,userId);//当前登录用户具有的二级权限
        List<Record> roleOneList=null;
        List<Record> userOneList=null;
        if ("role".equals(type)){//角色
            roleOneList=adminSystemService.selectPermissionByRoleId(id);
        }else if ("user".equals(type)){
            userOneList=adminSystemService.selectPermissionByUserId(id);
        }
        setAttr("roleOneList",roleOneList);
        setAttr("userOneList",userOneList);
        setAttr("twoList",twoList);
        setAttr("type",type);
        setAttr("id",id);
        //renderJsp("permissionTree.jsp");
        renderJsp("permissionList2.jsp");
    }
    /**
     * 三级按钮
     */
    public void threePermission(){
        String type=getPara("type");
        String id=getPara("id");
        String permissionId=getPara("twoPermissionId");
        String userId=getSession().getAttribute("userId").toString();
        List<Record> threeList=adminSystemService.threePermissionService(permissionId,userId);//当前登录用户具有的三级按钮
        List<Record> roleOneList=null;
        List<Record> userOneList=null;
        if ("role".equals(type)){//角色
            roleOneList=adminSystemService.selectPermissionByRoleId(id);
        }else if ("user".equals(type)){
            userOneList=adminSystemService.selectPermissionByUserId(id);
        }
        setAttr("roleOneList",roleOneList);
        setAttr("userOneList",userOneList);
        setAttr("threeList",threeList);
        setAttr("type",type);
        setAttr("id",id);
        //renderJsp("permissionTree.jsp");
        renderJsp("permissionList3.jsp");
    }

    /**
     * 修改用户/角色权限设置
     */
    public void settingUserOrRolePerssion(){
        String id=getPara("id");
        String type=getPara("type");
        String permissinId=getPara("permissinId");
        boolean state=getParaToBoolean("state");
        adminSystemService.settingUserOrRolePerssionService(id,type,permissinId,state);
    }


    /**
     * 添加角色
     */
    @Before(Tx.class)
    public void addRoleInfo() throws Exception{
        String userId= getSession().getAttribute("userId").toString();
        AdminSystemService adminSystemService = enhance(AdminSystemService.class);
        Map<String,String[]> map=getParaMap();
        ReturnData data = adminSystemService.addRoleInfo(map,userId);
        renderJson(data);
    }

    /**
     * 删除角色
     */
    @Before(Tx.class)
    public void roleDel() throws Exception{
        String userId= getSession().getAttribute("userId").toString();
        Map<String,String[]> map=getParaMap();
        AdminSystemService adminSystemService = enhance(AdminSystemService.class);
        ReturnData data = adminSystemService.roleDel(map,userId);
        renderJson(data);
    }

    /**
     * 查找角色信息
     */
    public void findRoleInfo(){
        String rid = getPara("rid");
        String userId= getSession().getAttribute("userId").toString();
        ReturnData data = adminSystemService.findRoleInfo(rid,userId);
        setAttr("data",data);
        setAttr("rid",rid);
        renderJsp("role-update.jsp");
    }

    /**
     * 修改角色信息
     */
    public void updateRole(){
        Map<String,String[]> map=getParaMap();
        ReturnData data = adminSystemService.updateRole(map);
        renderJson(data);
    }



    /**
     * 权限列表
     */
    public void adminRuleList(){
        String currentPage = getPara("currentPage");
        String limit = getPara("limit");
        String type=getPara("type");
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=adminSystemService.ruleList(map);
        PageUtil<List<Record>> menu= (PageUtil<List<Record>>) returnData.getData();
        ReturnData topReturnData=adminSystemService.topMenu();
        List<Record> topMenu= (List<Record>) topReturnData.getData();
        setAttr("topMenu",topMenu);
        setAttr("menu",menu);
        setAttr("currentPage",currentPage);
        setAttr("limit",limit);
        setAttr("type",type);
        renderJsp("adminRule.jsp");
    }
    /**
     * 保存权限
     */
    public void savePermission(){
        String id=getPara("id");
        String url=getPara("url");
        String parentid=getPara("parentid");
        String name=getPara("name");
        ReturnData returnData=adminSystemService.savePermissionService(id,parentid,url,name);
        renderJson(returnData);
    }
    /**
     * 根据ID删除权限
     */
    public void delPermission(){
        String id=getPara("id");
        Record record=new Record().set("id",id);
        boolean del=Db.delete("sys_permission","id",record);
        renderJson(del);
    }
    /**
     * 去权限编辑页面
     */
    public void editPermission(){
        String id=getPara("id");
        ReturnData returnData=adminSystemService.topMenu();
        Record record=Db.findFirst("SELECT *from sys_permission where id='"+id+"'");
        setAttr("rec",record);
        setAttr("top",returnData.getData());
        setAttr("id",id);
        renderJsp("adminRuleEdit.jsp");
    }
    /**
     * 权限类别表
     */
    public void permissionType(){
        ReturnData returnData=adminSystemService.rpermissionTypeService(getParaMap());
        Object oo=returnData.getData();
        setAttr("returnData",oo);
        renderJsp("admin-cate.jsp");
    }
    /**
     * 增加权限分类
     */
    public void saveRpermissionType(){
        ReturnData returnData=adminSystemService.saveRpermissionTypeService(getParaMap());
        renderJson(returnData);
    }
    /**
     * 权限分类-去修改页面
     */
    public void toRpermissionType(){
        String id=getPara("id");
        String sql="SELECT *from sys_permission_type where id='"+id+"'";
        Record record= Db.findFirst(sql);
        setAttr("record",record);
        renderJsp("cate-edit.jsp");
    }
    public void test(){
        renderJsp("test.jsp");
    }

    /**
     * 部门列表
     */
    public void department(){
        ReturnData returnData=adminSystemService.topDepartment();
        ReturnData all=adminSystemService.department();
        setAttr("topDepartment",returnData);
        setAttr("all",all);
        renderJsp("department.jsp");
    }
    /**
     * 部门编辑页面
     */
    public void departmentEdit(){
        String id=getPara("id");
        ReturnData all=adminSystemService.department();
        String sql="SELECT *from sys_department where id='"+id+"'";
        Record record=Db.findFirst(sql);
        setAttr("all",all.getData());
        setAttr("rec",record);
        renderJsp("departmentEdit.jsp");
    }
    /**
     * 保存部门
     */
    public void saveDepartment(){
        String id=getPara("id");
        String name=getPara("name");
        String userId=String.valueOf(getSession().getAttribute("userId"));
        ReturnData returnData=adminSystemService.saveDepartment(id,name,userId);
        renderJson(returnData);
    }
    /**
     * 删除部门
     */
    public void delPartment(){
        String id=getPara("id");
        Record record=new Record().set("id",id);
        boolean sa=Db.delete("sys_department","id",record);
        renderJson(sa);
    }
    /**
     * 系统管理员
     */
    public void adminList(){
        int currentPage=getParaToInt("currentPage");
        int size=getParaToInt("size");
        String userName=getPara("userName");
        String userCode=getPara("userCode");
        String userId=getSession().getAttribute("userId").toString();
        Record userRecord=cache.get(userId);
        String type=getPara("type");
        List<Record> list=adminSystemService.adminListService( currentPage, size, userName, userCode, type, userId);
        setAttr("list",list);
        setAttr("type",type);
        setAttr("userName",userName);
        setAttr("userCode",userCode);
        setAttr("currentPage",currentPage);
        renderJsp("adminList.jsp");
    }

    /**
     * 设置用户角色
     */
    public void goEditUserRole(){
        String id=getPara("id");
        String userId=getSession().getAttribute("userId").toString();
        List<Record> myList=adminSystemService.getRolesByAdminUserId(userId);
        List<Record> userList=adminSystemService.getRolesByUserId(id);
        setAttr("myList",myList);
        setAttr("userList",userList);
        setAttr("id",id);
        renderJsp("editUserRole.jsp");
    }
    /**
     * 保存用户角色
     */
    public void saveUserRole() throws Exception {
        String userId=getSession().getAttribute("userId").toString();
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=adminSystemService.saveUserRoleService(map,userId);
        renderJson(returnData);
    }


    /**
     * 去系统管理员编辑页面
     */
    public void goAdminEdit(){
        String userId=getSession().getAttribute("userId").toString();
        Record userRecord=cache.get(userId);
        String id=getPara("id");
        String type=getPara("type");
        String sql="SELECT * from sys_user where id='"+id+"'";
        Record record=Db.findFirst(sql);
        String sql1="SELECT\n" +
                "\tsr.id,\n" +
                "\tsr.`name`\n" +
                "FROM\n" +
                "\tsys_role sr\n" +
                "LEFT JOIN sys_user_role sur ON sr.id = sur.sys_user_id\n" +
                "WHERE\n" +
                "\tsur.sys_user_id = '"+id+"'";
        List<Record> onRole=Db.find(sql1);//该对象拥有的角色
        List<Record> roleList=userRecord.get("role");
        setAttr("rec",record);
        setAttr("id",id);
        setAttr("type",type);
        setAttr("roleList",roleList);
        setAttr("onRole",onRole);
        renderJsp("adminEdit.jsp");
    }

    /**
     * 保存系统管理员
     */
    @Before(Tx.class)
    public void saveAdmin(){
        String userId=getSession().getAttribute("userId").toString();
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=adminSystemService.saveAdminService(map,userId);
        renderJson(returnData);
    }
    public void getAdmin(){
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=adminSystemService.getAdmin(map);
        renderJson(returnData);
    }

    /**
     * 删除管理员
     */
    public void delAdmin(){
        String id=getPara("id");
        Record record=new Record().set("id",id);
        boolean del=Db.delete("sys_user","id",record);
        renderJson(del);
    }

    /**
     * 保存授权
     */
    public void saveAuthorization(){
        Map<String,String[]> map=getParaMap();
        ReturnData returnData=adminSystemService.saveUserPermission(map);
        renderJson(returnData);
    }
    /**
     * 部门具有的角色
     */
    public void departmentRoleList(){
        String id=getPara("id");
        Map map=adminSystemService.departmentRoleListService(id);
        renderJson(map);
    }


    public void buttonAjax(){
        String id=getPara("id");
        ReturnData returnData=adminSystemService.buttonAjaxService(id);
        setAttr("returnData",returnData);
        renderJsp("permissionAjax.jsp");
    }
    /**
     * 按钮权限管理
     */
    public void authorizationButton(){
        String id=getPara("id");
        String sql="SELECT *from sys_permission where parentid='"+id+"' and type='button'";
        List<Record> recordList=Db.find(sql);
        setAttr("parentid",id);
        setAttr("rec",recordList);
        renderJsp("ButtonPermission.jsp");
    }

    /**
     * 去按钮编辑页面
     */
    public void editAuthorizationButton(){
        String id=getPara("id");
        String parentid=getPara("parentid");
        String sql="SELECT *from sys_permission where id='"+id+"'";
        Record record=Db.findFirst(sql);
        setAttr("rec",record);
        setAttr("parentid",parentid);
        renderJsp("ButtonPermissionEdit.jsp");
    }
    /**
     * 保存按钮信息
     */
    public void saveAuthorizationButton(){
        String parentid=getPara("parentid");
        String id=getPara("id");
        String name=getPara("name");
        String url=getPara("url");
        ReturnData returnData=adminSystemService.saveAuthorizationButtonService(id,name,url,parentid);
        renderJson(returnData);
    }





    /**
     * 授权
     */
    public void authorization(){
        String type=getPara("type");
        String authorizationUserId=getPara("authorizationUserId");//被授权用户ID
        String userId=String.valueOf(getSession().getAttribute("userId"));
        ReturnData data = adminSystemService.findAllResource(type,userId);//查询当前用户权限
        ReturnData authorizationUser=adminSystemService.userPermissionByUserId(authorizationUserId);//被授权人ID
       // data=adminSystemService.authorizationService(data,authorizationUser);
        setAttr("data",data);
        setAttr("type",type);
        setAttr("authorizationUser",authorizationUser);
        setAttr("authorizationUserId",authorizationUserId);
        renderJsp("permission.jsp");
    }


    /**
     * 上传活动普通图片
     */
    public void uploadImages(){
        String images=getPara("images");
        String personFile=getPara("personFile");
        String orgId=getPara("orgId");
        Date date=new Date();
        String imgsName= date.getTime()+".jpg";
        FileUtil.decodeBase64ToImage(images, GlobalParameter.tempImgs+"201804GroupRebate/public/"+orgId+"-",imgsName);
        String endpoint = GlobalParameter.OOSUrl;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建
        String accessKeyId =GlobalParameter.accessKeyId;
        String accessKeySecret =GlobalParameter.accessKeySecret;
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传文件
        try {
            PutObjectResult result = ossClient.putObject(GlobalParameter.bucketName, "201804GroupRebate/public/" + orgId + "-" + imgsName, new File(GlobalParameter.tempImgs + "201804GroupRebate/public/" + orgId + "-" + imgsName));
            // 关闭client
            ossClient.shutdown();// 关闭client
        }catch (Exception e){
            ossClient.shutdown();// 关闭client
        }
        String imgPath="http://resource.xinrangj.com/201804GroupRebate/public/"+orgId+"-"+imgsName;
        renderJson(imgPath);
    }












    /**
     * layui回调函数请求方法
     */
    public void callBackImages(){
        Map map = new HashMap();
        map.put("code", 0);
        JSONObject json = JSONObject.fromObject(map);
        renderJson(json.toString());
    }


    /**
     * 去代理商机构数量编辑页面
     */
    public void goOrgNumberEdit(){
        String id=getPara("id");
        ReturnData returnData=adminSystemService.goOrgNumberEditService(id);
        setAttr("data",returnData.getData());
        setAttr("id",id);
        renderJsp("orgNumber.jsp");
    }

    /**
     * 保存机构数量
     */
    public void addOrgNumber(){
        String id=getPara("id");
        int addNumber=getParaToInt("addNumber");
        ReturnData returnData=adminSystemService.addOrgNumberService(id,addNumber);
        renderJson(returnData);
    }
    /**
     * 绑定个人微信
     */
    public void bindingWeiXin(){
        String userId=getSession().getAttribute("userId").toString();
        Map<String,String> map=new HashMap<>();
        int sceneId=Tools.getRandomNum()+Tools.getRandomNum();
        map.put("userId",userId);
        map.put("type","bindingWeiXin");
        cache.setex(sceneId,60*70,map);
        ApiResult result=QrcodeApi.createTemporary(60*60,sceneId);
        Syslog.info(result.getJson());
        String imgPath="";
        try {
            imgPath=QrcodeApi.getShowQrcodeUrl(result.getStr("ticket"));
        }catch (Exception e){
            Syslog.error(e);
        }
        setAttr("imgPath",imgPath);
        renderJsp("bindingWeiXin.jsp");
    }

    /***
     * 上传代理商二维码
     */
    public void uploaderweima(){

        renderJsp("uploadAdminerweima.jsp");
    }
    /**
     * 上传支付宝配置信息文件
     */
    public void uploadAlipayConfigTxt(){

        UploadFile file = getFile();

        String path = PropKit.get("rootPath") + "/upload/" + UtilUUID.getUUID() + "." +"txt";
        file.getFile().renameTo(new File(path));
        String imgUrl = path.replace(PropKit.get("rootPath"), "");
        Map map = new HashMap();
        map.put("code", "0");
        map.put("msg", "上传成功");
        Map data = new HashMap();
        data.put("src", imgUrl);
        data.put("title", "");
        map.put("data", data);
        renderJson(map);
    }

    /**
     * 超级管理员模式下的活动信息
     */
    public void adminActivityList(){

        String activityName=getPara("activityName");
        String orgName=getPara("orgName");
        String personTel=getPara("personTel");
        setAttr("activityName",activityName);
        setAttr("orgName",orgName);
        setAttr("personTel",personTel);
        renderJsp("adminActivityList.jsp");

    }

    /**
     * 超级管理员模式下的活动信息数据
     */
    public void adminActivityListDate(){
        Map<String,String[]> map=getParaMap();
        Map resultMap=adminSystemService.adminActivityList(map);
        renderJson(resultMap);
    }

    /**
     * 设置费用拓客费用（一个会员）
     */
    public void adminSetTalkMoney(){
        String id=getPara("id");
        String talkMoney=getPara("talkMoney");
        setAttr("id",id);
        setAttr("talkMoney",talkMoney);
        renderJsp("adminSetTalkMoney.jsp");
    }
    /**
     * 保存拓客费用（一个会员）
     */
    public void saveTalkMoney(){
        int talkMoney=getParaToInt("talkMoney")*100;
        String id=getPara("id");
        ReturnData returnData=new ReturnData();
        String sql="UPDATE yx_activity set talkMoney="+talkMoney+" where id="+id;
        int up=Db.update(sql);
        renderText(up+"");
    }




}



















